<script setup lang="ts">
import { ModalUtil } from '/@lib/utils/modal.ts'
import { MittBusUtil } from '/@lib/utils/mittBus.ts'
import { sys_normal_disable } from '/@/const/Options.ts'
import { usePagination } from '/@lib/hooks/usePagination.ts'
import { useLoading } from '/@lib/hooks/useLoading'
import { useForm } from '/@lib/hooks/useForm.ts'
import { formatDateTime } from '/@lib/utils/tool.ts'
import { UserQuery, UserVO } from '/@/api/system/sysUser/types'
import { ApiSysUser } from '/@/api/system/sysUser'
import AddOrUpdate from './AddOrUpdate.vue'
import OrgTree from './OrgTree.vue'
import AuthRole from './components/AuthRole.vue'

defineOptions({ name: 'sysUser' })

const { loading, showLoading, hideLoading } = useLoading()
const {
  pageNum, pageSize, total, setTotal, onChangeCurrent, onChangePageSize
} = usePagination(() => getTableList())
const queryFormRef = ref()
const { form: queryParams } = useForm<UserQuery>({
  pageNum: computed(() => pageNum.value),
  pageSize: computed(() => pageSize.value),
  userName: '',
  phoneNumber: '',
  status: '',
  deptId: '',
  roleId: ''
})
const tableRef = ref()
const tableData = ref([])
const tableFixed = ref('right')

const deptTitle = ref('')
const isCollapse = ref(false)

const AddOrUpdateRef = ref()
const AuthRoleRef = ref()

/** 搜索按钮操作 */
const handleQuery = () => {
  pageNum.value = 1
  getTableList()
}
/** 重置按钮操作 */
// const resetQuery = () => {
//   queryFormRef.value?.resetFields()
//   handleQuery()
// }

/** 新增按钮操作 */
const handleAdd = () => {
  AddOrUpdateRef.value.openAdd(queryParams.deptId)
}
/** 修改按钮操作 */
const handleUpdate = (row: UserVO) => {
  AddOrUpdateRef.value.openEdit(row)
}
/** 删除按钮操作 */
const handleDelete = async (row: UserVO) => {
  const _id = row.userId
  const _idLabel = row.userName
  try {
    await ModalUtil.confirm('是否确认删除名称为【 ' + _idLabel + ' 】的数据项？')
    showLoading()
    await ApiSysUser.remove(_id)
    ModalUtil.msgSuccess('删除成功')
    await getTableList()
  } finally {
    hideLoading()
  }
}
/** 状态修改  */
const handleStatusChange = async (row: UserVO) => {
  let text = row.status === '0' ? '启用' : '停用'
  try {
    await ModalUtil.confirm('确认要' + text + '【 ' + row.userName + ' 】吗?')
    showLoading()
    await ApiSysUser.changeStatus(row.userId, row.status)
    ModalUtil.msgSuccess(text + '成功')
  } catch (err) {
    row.status = row.status === '0' ? '1' : '0'
  } finally {
    hideLoading()
  }
}
/** 分配角色按钮操作 */
const handleAuthRole = async (row: UserVO) => {
  AuthRoleRef.value.open(row)
}

const getTableList = async () => {
  showLoading()
  try {
    const res = await ApiSysUser.page(queryParams)
    tableData.value = res.rows
    setTotal(res.total)
  } finally {
    hideLoading()
  }
}
onMounted(() => {
  MittBusUtil.on('onDeptSelectUser', (treeItem: any) => {
    deptTitle.value = treeItem.label
    queryParams.deptId = treeItem.id
    getTableList()
  })
})
onUnmounted(() => {
  MittBusUtil.unOn('onDeptSelectUser')
})
const successCallback = () => {
  getTableList()
}
</script>

<template>
  <div class="page-container">
    <el-container>
      <el-aside :class="{ 'is-collapse': isCollapse }">
        <OrgTree></OrgTree>
        <VipAsideFloatFold v-model="isCollapse" />
      </el-aside>

      <el-main class="no-padding margin-left flex-column">
        <el-card shadow="never" class="flex-column flex-auto no-margin-bottom">
          <template #header>
            <div class="header-title">{{ deptTitle ? deptTitle + '—用户列表' : '用户列表' }}</div>
          </template>

          <VipTableTool>
            <VipTableToolLeftPanel :span="8">
              <el-button icon="Plus" type="primary" @click="handleAdd">添加</el-button>
            </VipTableToolLeftPanel>

            <VipTableToolRightPanel :span="16">
              <el-form ref="queryFormRef" inline label-width="0" label-position="right">
                <el-form-item label="登录账号" prop="userName">
                  <el-input
                    v-model="queryParams.userName"
                    placeholder="请输入登录账号"
                    clearable
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="手机号码" prop="phoneNumber">
                  <el-input
                    v-model="queryParams.phoneNumber"
                    placeholder="请输入手机号码"
                    clearable
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>

                <!--   搜索按钮   -->
                <el-form-item>
                  <el-button plain type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <!--                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>-->
                </el-form-item>
              </el-form>
            </VipTableToolRightPanel>
          </VipTableTool>

          <div class="flex-auto">
            <el-table ref="tableRef" v-loading="loading" :data="tableData" border style="height: 100%">
              <!--              <el-table-column type="selection" width="50" align="center" />-->
              <el-table-column type="index" label="序号" width="55" align="center" />

              <!--  主内容   -->
              <el-table-column label="用户编号" align="center" prop="userId" />
              <el-table-column label="登录账号" align="center" prop="userName" show-overflow-tooltip />
              <el-table-column label="用户昵称" align="center" prop="nickName" show-overflow-tooltip />
              <el-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip />
              <el-table-column label="手机号码" align="center" prop="phoneNumber" show-overflow-tooltip />
              <el-table-column label="状态" align="center" prop="status" width="110">
                <template #default="scope">
                  <div class="flex-center">
                    <VipDictTag :options="sys_normal_disable" :value="scope.row.status" />
                    <el-switch
                      class="margin-left"
                      v-model="scope.row.status"
                      active-value="0"
                      inactive-value="1"
                      @change="handleStatusChange(scope.row)"
                    ></el-switch>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" width="120">
                <template #default="scope">
                  <span>{{ formatDateTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>

              <!--  操作栏   -->
              <el-table-column label="操作" :fixed="tableFixed" align="center" width="140">
                <!--                <template #header>-->
                <!--                  <el-checkbox v-model="table.fixed" label="固定操作列" true-value="right" />-->
                <!--                </template>-->
                <template #default="{ row }">
                  <el-space direction="vertical">
                    <el-space>
                      <el-button text type="primary" link @click="handleUpdate(row)">修改</el-button>
                      <el-button text type="danger" link @click="handleDelete(row)">删除</el-button>
                    </el-space>
                    <el-button text type="primary" link @click="handleAuthRole(row)">分配角色</el-button>
                  </el-space>
                </template>
              </el-table-column>

              <template #empty>
                <el-empty class="vip-data-empty" description="暂无数据" />
              </template>
            </el-table>
          </div>

          <VipPagination
            :current-page="pageNum"
            :page-size="pageSize"
            :total="total"
            @current-change="onChangeCurrent"
            @size-change="onChangePageSize"
          />
        </el-card>
      </el-main>
    </el-container>

    <AddOrUpdate ref="AddOrUpdateRef" @submit-success="successCallback"></AddOrUpdate>
    <AuthRole ref="AuthRoleRef" @submit-success="successCallback"></AuthRole>
  </div>
</template>

<style scoped lang="scss">
.el-aside {
  width: 240px !important;
  display: flex;
  height: 100%;
  overflow: hidden;

  &.is-collapse {
    width: 0 !important;
  }
}

:deep(.aside-float-fold) {
  left: 230px !important;

  &.is-collapse {
    left: 5px !important;
  }
}

:deep(.el-form--inline) {
  & .el-input {
    min-width: 200px !important;
    width: 200px !important;
  }
}
</style>
